package org.chnxi.study.concurrent.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class Demo02 {

    public static void main(String[] args) throws InterruptedException {
        MyBusiness mb = new MyBusiness();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"开始执行");
            mb.doMyBusiness2(false);
        },"Thread-1").start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"开始执行");
            mb.doMyBusiness2(false);
        },"Thread-3").start();

        TimeUnit.SECONDS.sleep(5);

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"开始执行");
            mb.doMyBusiness2(true);
        },"Thread-2").start();

    }

    static class MyBusiness{
        private ReentrantLock lock = new ReentrantLock();
        private Condition myCondition = lock.newCondition();
        private Object obj = new Object();

        public void doMyBusiness(boolean state){
            System.out.println(Thread.currentThread().getName()+"->doMybusiness");
            lock.lock();
            try{
                System.out.println(Thread.currentThread().getName()+"->doMybusiness with lock");
                if(!state){
                    System.out.println(Thread.currentThread().getName()+"->doMybusiness with false state");
                    myCondition.await();
                    System.out.println(Thread.currentThread().getName()+"->doMybusiness finished");
                }else{
                    System.out.println(Thread.currentThread().getName()+"->doMybusiness with true state");
                    myCondition.signalAll();
                }

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }

        public synchronized void doMyBusiness2(boolean state){
            System.out.println(Thread.currentThread().getName()+"->doMybusiness with lock");
            try{
                if(!state){
                    System.out.println(Thread.currentThread().getName()+"->doMybusiness with false state");
                    this.wait();
                    System.out.println(Thread.currentThread().getName()+"->doMybusiness finished");
                }else{
                    System.out.println(Thread.currentThread().getName()+"->doMybusiness with true state");
                    this.notifyAll();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

}
